package com.speechb.common.file;

import org.springframework.core.io.ClassPathResource;

import java.io.*;

public class FileUtil {
	public static void copyFile(String srcPath, String targetPath) throws Exception {
		File srcFile = new File(srcPath);
		File target = new File(targetPath);
		copyFile(srcFile,target);
	}
	/**
	 * 文件复制
	 * @param srcFile 源文件路径
	 * @param target 复制后存放路径
	 * @throws Exception
	 */
	public static String copyFile(File srcFile, File target) throws Exception {
		if (!srcFile.exists()) {
			throw new Exception("文件不存在！");
		}
		if (!srcFile.isFile()) {
			throw new Exception("不是文件！");
		}
		//判断目标路径是否是目录

		if(!target.exists()) {
			target.mkdirs();
		}


		// 获取源文件的文件名
		String srcPath = srcFile.getAbsolutePath();
		String fileName = srcPath.substring(srcPath.lastIndexOf("\\") + 1);
		//TODO:判断是否存在相同的文件名的文件
		File[] listFiles = target.listFiles();
		if(listFiles!=null&&listFiles.length>0) {
			for (File file : listFiles) {
				if (fileName.equals(file.getName())) {
					fileName += "_1";
				}
			}
		}
		String newFileName = target.getAbsolutePath() + File.separator + fileName;
		File targetFile = new File(newFileName);

		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(targetFile);
			//从in中批量读取字节，放入到buf这个字节数组中，
			// 从第0个位置开始放，最多放buf.length个 返回的是读到的字节的个数
			byte[] buf = new byte[8 * 1024];
			int len = 0;
			while ((len = in.read(buf)) != -1) {
				out.write(buf, 0, len);
				out.flush();
			}
			return fileName;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try{
				if(in != null){
				  in.close();
				}
			}catch(Exception e){
				 System.out.println("关闭输入流错误！");
			}
			try{
				if(out != null){
					out.close();
				}
			}catch(Exception e){
				System.out.println("关闭输出流错误！");
			}
		}
        return "";
	}
	//测试
	public static void main(String[] args) throws Exception {
		System.out.println(readerFileContent());
		//copyFile("C:\\Users\\admin\\Desktop\\test\\1-2.txt", "C:\\Users\\admin\\Desktop\\test");
	}

	public static String readerFileContent() {
		//获得系统属性集
		InputStream inputStream = null;
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		try {
			ClassPathResource classPathResource = new ClassPathResource("static/config.json");
			inputStream =classPathResource.getInputStream();
			br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
			String lineTxt = null;
			while ((lineTxt = br.readLine()) != null) {
				sb.append(lineTxt);
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}
}
